package com.example.samplemanagement.controller;

import com.example.samplemanagement.model.*;
import com.example.samplemanagement.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

// SampleController.java
@RestController
@RequestMapping("/api/samples")
public class SampleController {
    @Autowired
    private SampleRepository sampleRepository;

    @GetMapping
    public List<Sample> getAllSamples() {
        return sampleRepository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Sample> getSampleById(@PathVariable Long id) {
        Optional<Sample> sample = sampleRepository.findById(id);
        return sample.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Sample> createSample(@RequestBody Sample sample) {
        // CreationDate会在实体PrePersist中自动设置
        Sample savedSample = sampleRepository.save(sample);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedSample);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Sample> updateSample(@PathVariable Long id, @RequestBody Sample sampleDetails) {
        Optional<Sample> optionalSample = sampleRepository.findById(id);
        if (optionalSample.isPresent()) {
            Sample sample = optionalSample.get();
            sample.setSampleNumber(sampleDetails.getSampleNumber());
            sample.setSampleName(sampleDetails.getSampleName());
            sample.setCategory(sampleDetails.getCategory());
            sample.setDesigner(sampleDetails.getDesigner());
            sample.setStatus(sampleDetails.getStatus());
            // creationDate 不更新，因为它是创建时间
            Sample updatedSample = sampleRepository.save(sample);
            return ResponseEntity.ok(updatedSample);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSample(@PathVariable Long id) {
        if (sampleRepository.existsById(id)) {
            sampleRepository.deleteById(id);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

